package com.v1.video.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.MyLoginSubscribeActivity;
import com.v1.video.adapter.MyLoginSubscribeAdapter;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.MyloginSubscribeEntity;
import com.v1.video.domain.UserInfo4_4;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 订阅显示/粉丝显示
 * 
 * @author fengtao
 * 
 */
public class MyLoginSubscribeFragment extends V1BaseFragment {
	private final String TAG = "MyLoginSubscribeFragment";
	private PullToRefreshListView mRefreshListView;
	private ListView mListView;
	private MyLoginSubscribeAdapter mAdapter;
	private List<UserInfo4_4> mLstData = new ArrayList<UserInfo4_4>();
	private LayoutInflater mInflater;
	private View mView,mEmptyView;
	private int mCurIndex = 0;
	private Handler handlerConverse;
	public int flag = 0;
	/**视频总条数*/
	private int totalListNum = 0;
	/**当前页数*/
	private int curIndex = 0;
	/**总页数*/
	private int page_num = 0;
	private int count = 10;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		if (mView == null) {
			mInflater = inflater;
			mView = inflater
					.inflate(R.layout.fragment_my_login_video, container, false);
			initView();
			initData();
			setListener();
//		}
		return mView;
	}
	
	public MyLoginSubscribeFragment(Handler handlerConverse,int flag){
		this.handlerConverse= handlerConverse; 
		this.flag = flag;
	}

	private void initView() {
		mEmptyView = mInflater.inflate(R.layout.fragment_no_content, null);
		mRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.lv_listView);
		mListView = mRefreshListView.getRefreshableView();
		mRefreshListView.setScrollingWhileRefreshingEnabled(false);
		mRefreshListView.setMode(Mode.PULL_FROM_START);
	}

	private void initData() {
//		clickStatistics(Constant.HOME_CLASSIFICATION_ID, "首页频道-" + mCid);
		mAdapter = new MyLoginSubscribeAdapter(getActivity(),handlerConverse,flag);
//		mAdapter.setmType(mType);
		mListView.setAdapter(mAdapter);
		if (mRefreshListView != null) {
			mRefreshListView.doPullRefreshing(100);
		}
//		for(int i = 0; i < 20;i++){
//			UserInfo4_4 user = new UserInfo4_4();
//			user.setUid("00000"+i);
//			user.setNickname("用记000"+i);
//			user.setSignature("不想说"+i);
//			user.setType("0");
//			mLstData.add(user);
//		}
		mAdapter.setLstData(mLstData);
//		getServerData();
	}
	
	private void setListener() {
		mEmptyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.doPullRefreshing(100);
				}
			}
		});
		mRefreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				mCurIndex = 0;
				Logger.i(TAG, "下拉刷新");
				curIndex = 0;
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				}else{
					Message msg = handler.obtainMessage();
					msg.what = 0;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "上拉加载");
				curIndex++;
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				}else{
					Message msg = handler.obtainMessage();
					msg.what = 0;
					handler.sendMessage(msg);
				}
				
			}
		});
		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
	}
	
	
	private void getServerData(){
		if(flag == MyLoginSubscribeActivity.FLAG_SUBSCRIBE){//获取订阅用户
			getSubscribePlayerList();
		}else{//获取粉丝用户
			getFansList();
		}
	}
	/***
     * 获取粉丝列表
     */
    private void getFansList(){
    	String url = V1VideoHttpApi.GET_FANS_PLAYER_LIST() + "&uid="+LoginInfo.getInstance().getUserId()
				+"&p="+curIndex+"&s="+count+"&devid="+Constant.DEVICEID;
    	Logger.i(TAG, "粉丝列表Url ="+url);
		RequestManager.getInstance().getRequest(getActivity(), url, null, MyloginSubscribeEntity.class, 0, "MyLoginSubscribeFragment", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				if(object != null){
					MyloginSubscribeEntity entity = (MyloginSubscribeEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(getActivity(), "未知错误", Toast.LENGTH_SHORT);
//						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(getActivity(), header.getMessage(), Toast.LENGTH_SHORT);
//						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							if(entity.getBody().getPage_num() != null && entity.getBody().getPage_num().length() > 0){
								page_num = Integer.parseInt(entity.getBody().getPage_num());
							}else{
								page_num = 1;
							}
							Logger.i(TAG, "page_num=="+page_num);
							if(entity.getBody().getData() != null){
								if(curIndex == 0){
									mLstData.clear();
									mLstData.addAll(entity.getBody().getData());
								}else{
									mLstData.addAll(entity.getBody().getData());
								}
								mAdapter.setLstData(mLstData);
								if(curIndex < (page_num - 1)){
									
									Logger.i(TAG, "BOTH");
									mRefreshListView.setMode(Mode.BOTH);
								}else{
									Logger.i(TAG, "下拉刷新5 ");
									mRefreshListView.setMode(Mode.PULL_FROM_START);
								}
							}else{
								if(curIndex == 0){
									mListView.setEmptyView(mEmptyView);
								}else{
									if(mRefreshListView != null){
										mRefreshListView.setMode(Mode.PULL_FROM_START);
									}
								}
							}
							
						}else{
//							toast(header.getMessage());
						}
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				if(curIndex == 0){
					mListView.setEmptyView(mEmptyView);
				}
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
			}
		});
    }
	
	/***
     * 获取订阅用户列表
     */
    private void getSubscribePlayerList(){
    	String url = V1VideoHttpApi.GET_SUBSCRIBE_PLAYER_LIST() + "&uid="+LoginInfo.getInstance().getUserId()
				+"&p="+curIndex+"&s=20"+"&devid="+Constant.DEVICEID;
    	Logger.i(TAG, "订阅列表Url ="+url);
		RequestManager.getInstance().getRequest(getActivity(), url, null, MyloginSubscribeEntity.class, 0, "MyLoginSubscribeFragment", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				if(object != null){
					MyloginSubscribeEntity entity = (MyloginSubscribeEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(getActivity(), "未知错误", Toast.LENGTH_SHORT);
						mRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
						
//						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(getActivity(), header.getMessage(), Toast.LENGTH_SHORT);
						mRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
//						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody().getPage_num() != null && entity.getBody().getPage_num().length() > 0){
							page_num = Integer.parseInt(entity.getBody().getPage_num());
						}else{
							page_num = 1;
						}
						if(entity.getBody().getData() != null){
							if(curIndex == 0){
								mLstData.clear();
								mLstData.addAll(entity.getBody().getData());
							}else{
								mLstData.addAll(entity.getBody().getData());
							}
							mAdapter.setLstData(mLstData);
							if(curIndex < (page_num - 1)){
								mRefreshListView.setMode(Mode.BOTH);
							}else{
								mRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
							}
//							mAdapter.notifyDataSetChanged();
						}else{
							if(curIndex == 0){
								mListView.setEmptyView(mEmptyView);
							}else{
								if(mRefreshListView != null){
									mRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
								}
							}
						}
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				if(curIndex == 0){
					mListView.setEmptyView(mEmptyView);
				}
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				mRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
			}
		});
    }

	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case 0:
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				break;
			}
		}
		
	};
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart("MyLoginVideoFragment");
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd("MyLoginVideoFragment");
	}

	/**
	 * 刷新数据
	 */
	public void refresh() {
//		if (!TextUtils.isEmpty(mUserId)) {
//			mCurPage = 0;
//			new GetVideoInfoTask().execute();
//		}
	}

	/**
	 * 加载更多
	 */
	public void loadMore() {
//		if (!TextUtils.isEmpty(mUserId)) {
//			new GetVideoInfoTask().execute();
//		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		if (mCasdialog != null) {
//			if (mCasdialog.isShowing()) {
//				mCasdialog.dismiss();
//			}
//			mCasdialog = null;
//		}
		
		if (mAdapter != null) {
			mAdapter = null;
		}
	}
	
}
